<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="字段名称:" prop="fieldName">
        <el-input v-model="formData.fieldName" placeholder="请输入字段名称"
          :disabled="formType === 'view' || formData.systemField === '是'" />
      </el-form-item>
      <el-form-item label="字段备注:" prop="fieldNotes">
        <el-input v-model="formData.fieldNotes" placeholder="请输入字段备注" :disabled="formType === 'view'" />
      </el-form-item>
      <el-form-item label="使用场景:" prop="useScene">
        <el-select v-model="formData.useScene" clearable placeholder="请选择使用场景"
          :disabled="formType === 'view' || formData.systemField === '是'">
          <el-option v-for="item in useSceneList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="字段类型:" prop="fieldType">
        <el-select v-model="formData.fieldType" clearable placeholder="请选择字段类型"
          :disabled="formType === 'view' || formData.systemField === '是'">
          <el-option v-for="item in fieldTypeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="选项值:" prop="options">
        <div class="drag">
          <draggable :model-value="formData.options" :emptyItem="''" :view="formType === 'view' ? true : false">
            <template #default="{ element, index }">
              <div v-if="editingOption != index" class="drag-view drag-item">
                {{ element }}
                <Icon v-if="formType !== 'view'" icon="ep:edit" class="cursor-pointer text-blue-5"
                  @click.stop="startEditMode(index)" />
              </div>
              <div v-else class="drag-edit">
                <el-input v-model="formData.options[index]" @blur="endEditMode(index)" />
                <Icon v-if="formType !== 'view'" icon="ep:check" class="cursor-pointer text-blue-5"
                  @click.stop="endEditMode(index)" />
              </div>
            </template>
          </draggable>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm" v-if="formType !== 'view'">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
defineOptions({ name: 'ModuleForm' })
import * as ProjectApi from '@/api/project'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { currentRoute } = useRouter() // 路由对象
const { query } = unref(currentRoute)
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中:1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型:create - 新增；update - 修改
const formData = ref({
  projectId: parseInt(query.projectId),
  fieldName: '',
  fieldNotes: '',
  useScene: '2',
  fieldType: '1',
  options: []
})
const formRef = ref() // 表单 Ref
const checkOptions = async (rule: any, value: any, callback: any) => {
  await nextTick()
  if (value.length === 0) {
    return callback(new Error('选项值至少有一个非空的选项'))
  } else {
    value.forEach((item) => {
      if (item === '' || item.length > 50) {
        return callback(new Error('选项内容不能为空且不能多于50字'))
      }
    })
  }
  callback()
}
const formRules = reactive({
  fieldName: [{ required: true, message: '字段名称不能为空', trigger: 'blur' }],
  useScene: [{ required: true, message: '使用场景不能为空', trigger: 'change' }],
  fieldType: [{ required: true, message: '字段类型不能为空', trigger: 'change' }],
  fieldNotes: { max: 255, message: '字段备注不能多于255个字符', trigger: 'blur' },
  options: [{ validator: checkOptions, trigger: 'blur' }],
})
const editingOption = ref()
const fieldTypeList = ref([])
const useSceneList = ref([])
const getfieldTypeList = async () => {
  const data = await ProjectApi.getfieldTypeList()
  fieldTypeList.value = data
}
const getuseSceneList = async () => {
  const data = await ProjectApi.getuseSceneList()
  useSceneList.value = data
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  getfieldTypeList()
  getuseSceneList()
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      let data = await ProjectApi.getProjectModule({ id: id, projectId: query.projectId })
      formData.value = data
      if (formData.value.options === null) {
        formData.value.options = []
      }
      if (type === 'copy') {
        formData.value.id = null
      }
    } finally {
      formLoading.value = false
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    projectId: parseInt(query.projectId),
    fieldName: '',
    fieldNotes: '',
    useScene: '2',
    fieldType: '1',
    options: []
  }
  formRef.value?.resetFields()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const startEditMode = (index) => {
  editingOption.value = index;
}
const endEditMode = (index) => {
  // if (formData.value.options[index].trim() !== '') {
  editingOption.value = null;
  // } else {
  //   removeOption(index);
  // }
}
const removeOption = (index) => {
  formData.value.options.splice(index, 1);
}
watch(
  () => formData.value.options,
  () => {
    let index = formData.value.options.length - 1
    if (formData.value.options[index] === '') {
      startEditMode(index)
    }
  },
  {
    deep: true
  }
)

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
    }
    if (formType.value === 'create') {
      await ProjectApi.createProjectModule(data)
      message.success(t('common.createSuccess'))
    } else if (formType.value === 'copy') {
      await ProjectApi.createProjectModule(data)
      message.success('复制成功')
    } else {
      await ProjectApi.updateProjectModule(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
<style scoped lang="scss">
.drag {
  width: 100%;

  &-edit,
  &-view {
    display: flex;
    width: calc(100% - 45px);
    justify-content: space-between;
    align-items: center;

    .el-input {
      margin-right: 5px;
    }
  }

  .drag-item {
    /* 你的样式 */
    -webkit-user-select: none;
    /* Safari */
    -moz-user-select: none;
    /* Firefox */
    -ms-user-select: none;
    /* IE/Edge */
    user-select: none;
    /* 标准语法 */
  }
}
</style>
